﻿using FileSynchronization.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace FileSynchronization
{
    public class FileSubscriptionApi
    {
        string Url;

        public FileSubscriptionApi(string url)
        {
            Url = url;
        }

        public List<WatchDto> GetAllWatchs()
        {
            return HttpGet<List<WatchDto>>($"{Url}/File/GetAllWatchs");
        }

        public WatchDetailDto GetWatchDetail(string id, string path)
        {
            var args = new GetWatchDetailArgs
            {
                Id = id,
                Path = path
            };

            return HttpPost<GetWatchDetailArgs, WatchDetailDto>($"{Url}/File/GetWatchDetail", args);
        }

        public List<FileDetailDto>? GetFileDetails(string id, string path, List<string> files)
        {
            if (files?.Any() != true)
                return null;

            var args = new GetFileDetailsArgs
            {
                Id = id,
                Path = path,
                Files = files.ToArray(),
            };

            return HttpPost<GetFileDetailsArgs, List<FileDetailDto>?>($"{Url}/File/GetFileDetails", args);
        }

        public void Download(string local, string id, string path)
        {
            Download(local, $"{Url}/File/Download?path={path}&id={id}");
        }

        void Download(string local, string url)
        {
            HttpClient httpClient = new HttpClient();

            var resp = httpClient.GetAsync(url).Result;

            using (var respStream = resp.Content.ReadAsStream())
            {
                using (var fs = new FileStream(local, FileMode.Create))
                {
                    respStream.CopyTo(fs);
                }
            }
        }


        TResul HttpPost<TRequest, TResul>(string url, TRequest request)
        {
            HttpClient httpClient = new HttpClient();

            var json = JsonConvert.SerializeObject(request);

            var resp = httpClient.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json")).Result;
            var body = resp.Content.ReadAsStringAsync().Result;

            return JsonConvert.DeserializeObject<TResul>(body);
        }

        T HttpGet<T>(string url)
        {
            HttpClient httpClient = new HttpClient();

            var resp = httpClient.GetAsync(url).Result;
            var body = resp.Content.ReadAsStringAsync().Result;

            return JsonConvert.DeserializeObject<T>(body);
        }
    }

    public class WatchDto
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
}
